const net = require('net');

let host = '127.0.0.1';
let port = '8080';

let server = net.createServer((sock) => {

    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);

    sock.on('data', (data) => {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write('You said:', data);
    })

    sock.on('close', () => {
        console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
    })

    sock.on('error',(err)=>{   //加了错误事件  服务端不会因为客户端异常关闭而关闭  
        console.log('error:',err);
    })

    setTimeout(() => {
        sock.destroy();//3s后毁掉该次链接
    }, 100000); 

})

server.listen(port,host);

console.log('Server listening on ' + host +':'+ port);


/*其他写法-实现同样道理*/
// var server = net.createServer();
// server.listen(PORT, HOST);
// console.log('Server listening on ' +
//     server.address().address + ':' + server.address().port);

// server.on('connection', function(sock) {

//     console.log('CONNECTED: ' +
//          sock.remoteAddress +':'+ sock.remotePort);
//     // 其它内容与前例相同
// });
